<?php
// connect to the database
include "connect.php";
?>

<html>
<head>
<title>Interactive Travel Map</title>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8rc3.custom.min.js"></script>
<link type="text/css" href="jquery-ui-1.8rc3.custom.css" rel="stylesheet" />

<script>

// checks if the user provided all the data for adding a new location
function check()
{
	if (document.getElementById('lat').value == "" || document.getElementById('long').value == "" || document.getElementById('address').value == "")
	{
		alert("Click on the map to choose location!");
		return false;
	}

	if (document.getElementById('name').value == "")
	{
		alert("Write a name for the new location!");
		return false;
	}
	
	if (document.getElementById('description').value == "")
	{
		alert("Write a description for the new location!");
		return false;
	}

	
	

	return true;
}

</script>

<style>
html
{
  height: 100%;
}
                         
body
{
  background: #eeeeee;
  height: 100%;
  margin: 10;
  padding: 0;
  line-height: 150%;
}

*
{
  font-size: 10pt; 
  font-family: Tahoma, Verdana, sans-serif; 
  color: #000000;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
	var geocoder;
	var map;
	
	// initializing the map
	function initialize()
	{
		// define map center
		var latlng = new google.maps.LatLng(57.279043,29.355469);
		// define map options
		var myOptions = 
		{
			zoom: 3,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.HYBRID,
			scaleControl: true,
			navigationControl: true,
			navigationControlOptions: {
				style: google.maps.NavigationControlStyle.SMALL
			},
			mapTypeControl: true,
			mapTypeControlOptions: {
				style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
			}
		};
		
		// initialize map
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		
		// add event listener for when a user clicks on the map
		google.maps.event.addListener(map, 'click', function(event) {
			findAddress(event.latLng);
		});
	}
	
	// finds the address for the given location
	function findAddress(loc)
	{
		geocoder = new google.maps.Geocoder(); 
		
		if (geocoder) 
		{
			geocoder.geocode({'latLng': loc}, function(results, status) 
			{
				if (status == google.maps.GeocoderStatus.OK) 
				{
					if (results[0]) 
					{
						address = results[0].formatted_address;
						
						// fill in the results in the form
						document.getElementById('lat').value = loc.lat();
						document.getElementById('long').value = loc.lng();
						document.getElementById('address').value = address;
					}
				} 
				else 
				{
					alert("Geocoder failed due to: " + status);
				}
			});
		}
	}
	
	// initialize the array of markers
	var markers = new Array();
	
	// the function that adds the markers to the map
	function addMarkers()
	{
		// get the values for the markers from the hidden elements in the form
		var lats = document.getElementById('lats').value;
		var lngs = document.getElementById('lngs').value;
		var addresses = document.getElementById('addresses').value;
		var names = document.getElementById('names').value;
		var descrs = document.getElementById('descrs').value;
		var photos = document.getElementById('photos').value;
		var user_names = document.getElementById('user_names').value;
		var user_locs = document.getElementById('user_locs').value;
		
		var las = lats.split(";;")
		var lgs = lngs.split(";;")
		var ads = addresses.split(";;")
		var nms = names.split(";;")
		var dss = descrs.split(";;")
		var phs = photos.split(";;")
		var usrn = user_names.split(";;")
		var usrl = user_locs.split(";;")
		
		// for every location, create a new marker and infowindow for it
		for (i=0; i<las.length; i++)
		{
			if (las[i] != "")
			{
				// add marker
				var loc = new google.maps.LatLng(las[i],lgs[i]);
				var marker = new google.maps.Marker({
					position: loc, 
					map: window.map,
					title: nms[i]
				});
				
				markers[i] = marker;
				
				var contentString = [
				  '<div id="tabs">',
				  '<ul>',
					'<li><a href="#tab-1"><span>photo</span></a></li>',
					'<li><a href="#tab-2"><span>description</span></a></li>',
					'<li><a href="#tab-3"><span>location</span></a></li>',
				  '</ul>',
				  '<div id="tab-1">',
					'<p><h1>'+nms[i]+'</h1></p>',
					'<p><img src="./photos/'+phs[i]+'"/></p>'+
				  '</div>',
				  '<div id="tab-2">',
				   '<p><h1>'+nms[i]+'</h1></p>',
				   '<p>Added by: '+usrn[i]+' from '+usrl[i]+'</p>'+
				   '<p>'+dss[i]+'</p>'+
				  '</div>',
				  '<div id="tab-3">',
					'<p><h1>'+nms[i]+'</h1></p>',
					'<p>Address: '+ads[i]+'</p>'+
					'<p>Location: '+loc+'</p>'+
				  '</div>',
				  '</div>'
				].join('');
				
				var infowindow = new google.maps.InfoWindow;
				
				bindInfoWindow(marker, window.map, infowindow, contentString);
			}
		}
	}
	
	// make conection between infowindow and marker (the infowindw shows up when the user goes with the mouse over the marker)
	function bindInfoWindow(marker, map, infoWindow, contentString)
	{
		google.maps.event.addListener(marker, 'mouseover', function() {
			
			map.setCenter(marker.getPosition());
			
			infoWindow.setContent(contentString);
			infoWindow.open(map, marker);
			$("#tabs").tabs();
		 });
	}
	
	// highlighting a marker
		// make the marker show on top of the others
		// change the selected markers icon
	function highlightMarker(index)
	{
		// change zindex and icon
		for (i=0; i<markers.length; i++)
		{
			if (i == index)
			{
				markers[i].setZIndex(10);
				markers[i].setIcon('http://www.google.com/mapfiles/arrow.png');
			}
			else
			{
				markers[i].setZIndex(2);
				markers[i].setIcon('http://www.google.com/mapfiles/marker.png');
			}
		}
	}
</script>
</head>

<body onload="initialize(); addMarkers()">

	<?php
	// adding a new location to the db
	if (isset($_POST['name']))
	{
		$name = $_POST['name'];
		$description = $_POST['description'];
		$photo = $_FILES['photo']['name'];
		
		$user_name = $_POST['user_name'];
		$user_location = $_POST['user_location'];
		
		$lat = $_POST['lat'];
		$long = $_POST['long'];
		$address = $_POST['address'];

		// generate id
		$id = 1;
		$result = mysql_query("select max(id) from locations");
		if (mysql_num_rows($result) != 0)
		{
			$row = mysql_fetch_array($result);
			$id = $row['max(id)']+1;
		}
		
		// photo name
		$photo_name = "./photos/".$id."_photo.jpg";
		
		// sql query to add location
		$result = mysql_query("insert into locations (`id`, `name`, `latitude`, `longitude`, `address`, `photo`, `description`, `user_name`, `user_location`) 
									values ('$id','$name', '$lat', '$long', '$address', '$photo_name', '$description', '$user_name', '$user_location')");
									
		//upload photo
		move_uploaded_file($_FILES['photo']['tmp_name'],"./photos/".$id."_photo.jpg");
		
		//resize photo
		$simg = imagecreatefromjpeg("./photos/".$id."_photo.jpg");   
		$currwidth = imagesx($simg);   
		$currheight = imagesy($simg);   
		
		// new width = 200px
		$twidth = "200";
		$zoom = $twidth / $currwidth;   
		$newwidth = $twidth;   
		$newheight = $currheight * $zoom;   

		$dimg = imagecreatetruecolor($newwidth, $newheight);    
		imagecopyresampled($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   
		imagejpeg($dimg, "./photos/".$id."_photo.jpg"); 

		// update photo name
		$result = mysql_query("update locations set `photo`='".$id."_photo.jpg' where id=".$id);
	}
	?>

	<div id="address_details" style="width:100%; height:10%;">
		<h1><center>Interactive Travel Map</center></h1>
		<?php
		$locations = mysql_query("select * from locations");
		$nr_locations = mysql_num_rows($locations);
		?>
		<br/>Click on the map to add a new location! Total locations added: <?php echo $nr_locations;?>
	</div>
	
	<br/>
		<div id="add" style="width:25%; height:86%;  float:left;">
			
				<center><h1>Add a new location</h1></center>

				<br/>

				<form action="index.php" method="post" name="add" id="add" enctype="multipart/form-data" onsubmit="return check();">

				<table align="center">
					<tr>
						<td><b>Name: </b></td>
						<td>&nbsp;</td>
						<td><input name="name" id="name" type="text" size="30"/></td>
					</tr>
					<tr>
						<td><b>Coordinates: </b></td>
						<td>&nbsp;</td>
						<td>lat: <input name="lat" id="lat" type="text" size="15" readonly/><br/>long: <input name="long" id="long" type="text" size="15" readonly/></td>
					</tr>
					<tr>
						<td><b>Address: </b></td>
						<td>&nbsp;</td>
						<td><input name="address" id="address" type="text" size="30" readonly/></td>
					</tr>
					<tr>
						<td><b>Description: </b></td>
						<td>&nbsp;</td>
						<td><textarea name="description" id="description" cols="30" rows="7"/></textarea></td>
					</tr>
					<tr>
						<td><b>Photo: </b></td>
						<td>&nbsp;</td>
						<td><input id="photo" name="photo" type="file"/></td>
					</tr>
					<tr>
						<td colspan="3" align="center">&nbsp;</td>
					</tr>
					<tr>
						<td colspan="3" align="center">
							<table>
								<tr>
									<td colspan="3"><b>Who are you?</b></td>
								</tr>
								<tr>
									<td>Name:</td>
									<td>&nbsp;</td>
									<td><input name="user_name" id="user_name" type="text" size="25"/></td>
								</tr>
								<tr>
									<td>Location:</td>
									<td>&nbsp;</td>
									<td><input name="user_location" id="user_location" type="text" size="25"/></td>
								</tr>
							</table>
						</td>
					</tr>
					<tr>
						<td colspan="3" align="center">&nbsp;</td>
					</tr>
					<tr>
						<td colspan="3" align="center"><input type="submit" value="Add"/></td>
					</tr>
				</table>

				</form>
			
			</div>
			<div id="map_canvas" style="width:65%; height:86%; float:left;"></div>
			
			<div id="locations" style="width:10%; height:86%; float:right; text-align: center">
			
			<center><h1>Location list</h1></center>

			<br/>

			<?php
			// find locations from db
				// save data for locations
			$lats = "";			// string with latitude values
			$lngs = "";			// string with longitude values
			$addresses = "";	// string with address values
			$names = "";		// string with names
			$descrs = "";		// string with descriptions
			$photos = "";		// string with photo names
			$user_names = "";	// string with user names
			$user_locs = "";	// string with user locations
			$i=0;
			
			// take the locations from the db one by one
			while ($locat = mysql_fetch_array($locations))
			{
				// add lcoation data to info strings
				$lats .= $locat['latitude'].";;";
				$lngs .= $locat['longitude'].";;";
				$addresses .= $locat['address'].";;";
				$names .= $locat['name'].";;";
				$descrs .= $locat['description'].";;";
				$photos .= $locat['photo'].";;";
				$user_names .= $locat['user_name'].";;";
				$user_locs .= $locat['user_location'].";;";
				// show the location name in the right of the map with link that calls the highlightMarker function
				?>
				<a onmouseover="highlightMarker(<?php echo $i;?>)"><?php echo $locat['name'];?></a> <br/>
				<?php
				$i++;
			}
			// hidden inputs for saving the info for all the locations in the db
			?>
			<input type="hidden" value="<?php echo $lats;?>" id="lats" name="lats"/>
			<input type="hidden" value="<?php echo $lngs;?>" id="lngs" name="lngs"/>
			<input type="hidden" value="<?php echo $addresses;?>" id="addresses" name="addresses"/>
			<input type="hidden" value="<?php echo $names;?>" id="names" name="names"/>
			<input type="hidden" value="<?php echo $descrs;?>" id="descrs" name="descrs"/>
			<input type="hidden" value="<?php echo $photos;?>" id="photos" name="photos"/>
			<input type="hidden" value="<?php echo $user_names;?>" id="user_names" name="user_names"/>
			<input type="hidden" value="<?php echo $user_locs;?>" id="user_locs" name="user_locs"/>
			</div>
	
</body>
</html>